﻿using System;
using System.Collections.Generic;
using CefSharp.WinForms;
using CefSharp;
using DHZG;
using System.Threading;
namespace warehouse.browserevent
{
    class RevolvingCommand
    {
        public Dictionary<string, CustomerTcpClient> clients = new Dictionary<string, CustomerTcpClient>();
        public ChromiumWebBrowser chrome;
        Dictionary<string, bool> start_stop = new Dictionary<string, bool>();
        public IJavascriptCallback callBack=null;
        TcpServer tcpServer;
        // 为保证线程安全，使用一个锁来保护_task的访问
        //readonly static object _locker = new object();
        public RevolvingCommand(ChromiumWebBrowser chrome, TcpServer server)
        {
            this.chrome = chrome;
            tcpServer = server;
            tcpServer.TcpServerPlayinfo += TcpServer_TcpServerPlayinfo;
        }

        private void TcpServer_TcpServerPlayinfo(string msg)
        {
            if (callBack != null)
            {
                ResponseEntity response = new ResponseEntity();
                response.result = "0";
                if (msg.Contains("_"))
                {
                    Console.WriteLine(msg + "===========hello============");
                    response.code = "SendInventory";
                    response.data = msg;
                    response.msg = "盘点";
                    callBack.ExecuteAsync(response);
                }else if (msg.Contains("#"))
                {
                    //盘点结束
                }
                else if (msg.Contains("$"))
                {
                    //设备异常
                    response.code = "SendInventory";
                    response.result = "1";
                    response.msg = "扫描设备异常";
                    callBack.ExecuteAsync(response);
                }


            }
        }

        public CustomerTcpClient getClientEvent(string ip, int port)
        {
            CustomerTcpClient customerTcpClient = new CustomerTcpClient();
            customerTcpClient.tcpClient = new TcpClient(ip, port);
            start_stop.Add(ip + "_" + port, false);
            return customerTcpClient;
        }
        public void Command(object jsonText)
        {
            RequestEntity param = (RequestEntity)jsonText;
            CustomerTcpClient customerTcpClient = getClientEvent(param.ip, int.Parse(param.port));
            TcpClient tcpClient = customerTcpClient.tcpClient;
            ResponseEntity response = new ResponseEntity();
            response.code = param.code;
            response.result = "0";
            var connection = tcpClient.Connect();
            callBack = null;
            if (connection)
            {
                switch (param.code)
                {
                    case "CloseDoor":
                        tcpClient.CloseDoor(param.carbinetId);
                        response.msg="关闭门";
                        break;
                    case "OpenDoor":
                        tcpClient.OpenDoor(param.carbinetId);
                        response.msg = "打开门";
                        break;
                    case "MoveLayer":
                        tcpClient.MoveLayer(param.carbinetId, param.layer);
                        response.msg = "走层";
                        break;
                    case "OpenAndMove":
                        OpenAndMoveAndLed(tcpClient, param, response,false);
                        break;
                    case "OpenAndMoveAndLed":
                        OpenAndMoveAndLed(tcpClient,param,response,true);
                        break;
                    case "SendInventory":
                        callBack = param.callBack;
                        SendInventory(tcpClient, param, response);
                        break;
                    case "SendInventoryAll":
                        callBack = param.callBack;
                        customerTcpClient.start_stop = true;
                        start_stop.Add(param.ip + "_" + param.port, true);
                        SendInventoryAll(customerTcpClient, param, response);
                        break;
                    case "StopInventory":
                        start_stop.Add(param.ip + "_" + param.port, false);
                        break;
                    case "CloseLed":
                        callBack = param.callBack;
                        tcpServer.SendLed(param.antennaIp, "");
                        break;
                }
                tcpClient.close();
            }else
            {
                response.result = "0";
                response.msg = "tcp连接失败！";
            }
            if (param.callBack != null && callBack==null)
            {
                param.callBack.ExecuteAsync(response);
            }
          
            
        }
        /// <summary>
        /// 开门，走层，开灯
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="param"></param>
        /// <param name="response"></param>
        public void OpenAndMoveAndLed(TcpClient tcpClient, RequestEntity param, ResponseEntity response,bool openLed)
        {

            string []status = tcpClient.SearchDoorState(param.carbinetId).Split('_');
            string doorStatus = status[0];
            string currentLayer = status[1];
            string openStatus = "1";
            int compareLayer = 0;
            //1 已经打开
            if ("1".Equals(doorStatus))
            {
                openStatus = "0";
                Console.WriteLine("门是打开状态");
            }
            else
            {
                Console.WriteLine("执行：开门命令");
                openStatus = tcpClient.OpenDoor(param.carbinetId);
                if ("0".Equals(openStatus))
                {
                  
                    Thread.Sleep(20000);
                }
                else
                {
                    response.result = "1";
                    response.msg = "打开柜门失败";
                }
            }
            compareLayer = Math.Abs(int.Parse(param.layer) - int.Parse(currentLayer));
            Console.WriteLine("目标层与当前层差值：" + compareLayer);
            if (compareLayer > 0)
            {
                Console.WriteLine("执行：走层命令");
                string move = tcpClient.MoveLayer(param.carbinetId, param.layer);
                if (!"0".Equals(move))
                {
                    response.result = "1";
                    response.msg = "移动层失败";
                }else
                {
                    Console.WriteLine("执行：开灯命令");
                    if (openLed)
                    {
                        tcpServer.SendLed(param.antennaIp, param.ledNum);
                    }
                }
            }
            else
            {
                if (openLed)
                {
                    tcpServer.SendLed(param.antennaIp, param.ledNum);
                }
            }
        }

        /// <summary>
        /// 扫描当前层
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="param"></param>
        /// <param name="response"></param>
        public void SendInventory(TcpClient tcpClient, RequestEntity param, ResponseEntity response)
        {
            string[] status = tcpClient.SearchDoorState(param.carbinetId).Split('_');
           
            string doorStatus = status[0];
            string currentLayer = status[1];
            Console.WriteLine("门状态：" + doorStatus);
            int compareLayer  = Math.Abs(int.Parse(param.layer) - int.Parse(currentLayer));
            Console.WriteLine("目标层与当前层差值：" + compareLayer);
            if (compareLayer > 0)
            {
                string move = tcpClient.MoveLayer(param.carbinetId, param.layer);
                Thread.Sleep(compareLayer*8000);
                if (!"0".Equals(move))
                {
                    response.result = "1";
                    response.msg = "移动层失败";
                }
            }
            tcpServer.SendInventory(param.antennaIp,currentLayer);
        }

        /// <summary>
        /// 盘点一个柜子
        /// </summary>
        /// <param name="tcpClient"></param>
        /// <param name="param"></param>
        /// <param name="response"></param>
        public void SendInventoryAll(CustomerTcpClient customerTcpClient, RequestEntity param, ResponseEntity response)
        {
            TcpClient tcpClient = customerTcpClient.tcpClient;
            string[] status = tcpClient.SearchDoorState(param.carbinetId).Split('_');
            string doorStatus = status[0];
            string currentLayer1 = status[1];
            string openStatus = "1";
            Console.WriteLine("门状态：" + doorStatus);
            Console.WriteLine("当前层：" + currentLayer1);
            if ("1".Equals(doorStatus))
            {
                openStatus = "0";
                Console.WriteLine("门是打开状态");
            }
            else
            {
                Console.WriteLine("执行：开门命令");
                openStatus = tcpClient.OpenDoor(param.carbinetId);
                if ("0".Equals(openStatus))
                {
                    Thread.Sleep(20000);
                }
                else
                {
                    response.result = "1";
                    response.msg = "打开柜门失败";
                }
            }
            if ("0".Equals(openStatus))
            {
                int layer_all = int.Parse(param.layer);//作为总层数 参数
                Console.WriteLine("执行第:" + currentLayer1);
                tcpServer.SendInventory(param.antennaIp,currentLayer1);
                Thread.Sleep(5000);
                int currentLayer = int.Parse(currentLayer1);
                for (int i = 1; i < layer_all; i++)
                {
                    if (start_stop[param.ip+"_"+param.port])
                    {
                        currentLayer = (currentLayer % layer_all) + 1;
                        Console.WriteLine("目标层:" + currentLayer);
                        string move = tcpClient.MoveLayer(param.carbinetId, currentLayer.ToString());
                        Thread.Sleep(9000);
                        if ("0".Equals(move))
                        {
                            tcpServer.SendInventory(param.antennaIp, currentLayer.ToString());
                            Thread.Sleep(5000);
                        }
                    }
                }
            }
        }
    }
}
